#pragma once
#include <iostream>
#include <string>
#include "Log.hpp"
#include <functional>
#include "Reactor.hpp"
#include "InitAddr.hpp"
using namespace std;
class Connection;
class Reactor;
using func_t = function<void(Connection*)>;



class Connection {
public :
    Connection(int sockfd, uint32_t event, Reactor* r)
        :_sockfd(sockfd)
        ,_event(event)
        ,_addr(nullptr)
        ,_R(r)
    {

    }
    // 注册对应的回调方法
    void RegisterFunc(func_t recver, func_t sender, func_t excepter) {
        _recver = recver;
        _sender = sender;
        _excepter = excepter;
    }

    void SetAddr(struct sockaddr_in addr) {
        _addr = new InitAddr(addr);
    }

    string Get_Info() {
        return _addr->get_Info();
    }
    
    int SockFd() {
        return _sockfd;
    }
    uint32_t Event() {
        return _event;
    }
    void SetEvent(uint32_t events) {
        _event = events;
    }

    void AddInbuffer(string message) {
        _inbuffer += message;
    }
    void AddOutbuffer(string message) {
        _outbuffer += message;
    }

    string& Inbuffer() {
        return _inbuffer;
    }
    string& Outbuffer() {
        return _outbuffer;
    }

    bool OutbufferEmpty() {
        return _outbuffer.empty();
    }

    ~Connection() {

    }

private :
    int _sockfd; // 文件描述符
    string _inbuffer; // 写缓冲区
    string _outbuffer; // 发送缓冲区
    uint32_t _event; // 需要关心的事件
    InitAddr* _addr; // 维护客户端的信息
public :
    func_t _recver; // 处理写事件的回调对象
    func_t _sender; // 处理读事件的回调对象
    func_t _excepter; // 处理异常的回调对象
    Reactor* _R;
};


class ConnectionFactory {
public :
    static Connection* BuildListenConnection(int sockfd, uint32_t event, Reactor* r, func_t recver) {
        Connection* listen_connection = new Connection(sockfd, event, r);
        listen_connection->RegisterFunc(recver, nullptr, nullptr);
        return listen_connection;
    }

    static Connection* BuildNormalConnection(int sockfd, uint32_t event, Reactor* r, func_t recver, func_t sender, func_t excepter) {
        Connection* normal_connection = new Connection(sockfd, event, r);
        normal_connection->RegisterFunc(recver, sender, excepter);
        return normal_connection;
    }
    
};